//
//  MeViewController.m
//  CleanerAir_Project
//
//  Created by mac on 16/4/28.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "MeViewController.h"
#import "CALoginViewController.h"
#import "CAPersonalBusinessViewController.h"
#import "UseAgreementVC.h"
#import "MeTableViewCell.h"


@interface MeViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    NSArray *_listNameAry;
    NSArray *_viewControllerNameAry;
    
}


@property (weak, nonatomic) IBOutlet UIImageView *meInfoImageView;

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nickNameLabel;
//个性签名
@property (weak, nonatomic) IBOutlet UILabel *individualitySignatureLabel;


@property (weak, nonatomic) IBOutlet UITableView *listTableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headImageH;

@end

@implementation MeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    
    self.listTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self initSubArray];
    
    
    [self.meInfoImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personalInformation)]];
    [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personalInformation)]];
    [self.nickNameLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personalInformation)]];
    [self.individualitySignatureLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personalElucidation)]];
    
    
    self.headImageH.constant = (MAIN_WIDTH / 750.0) * 400;
    
    NSLog(@"%f",self.headImageH.constant);
    NSLog(@"%f",self.headImageView.height);
  
    self.headImageView.layer.cornerRadius =  MAIN_WIDTH >= 375 ? self.headImageH.constant * 0.25 : self.headImageView.height * 0.5;
    self.headImageView.layer.borderWidth = 1;
    self.headImageView.layer.borderColor = [UIColor grayColor].CGColor;

}

#pragma mark -- 修改查看 个人信息 & 个人说明
- (void)personalInformation{
    
    //    判断是否登录
    if (![self isLogin]) {
        [self login];
        
    }else{
        
        UIStoryboard *personalInfo = [UIStoryboard storyboardWithName:@"PersonalInfomation" bundle:nil];
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:[personalInfo instantiateInitialViewController] animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }
    
}

- (void)personalElucidation{
    
}

- (BOOL)isLogin{
    
    if ([[LoginSingleton sharedLoginSingleton].token isEqualToString:@""] || [LoginSingleton sharedLoginSingleton].token == nil) {
        
        self.headImageView.image = [UIImage imageNamed:@"克林埃尔.png"];
        self.nickNameLabel.text = @"克林埃尔";
        self.individualitySignatureLabel.text = @"您的支持，是我们前进的最大动力！ಠ౪ಠ";
        
        return NO;
    }
    
    return YES;
}

#pragma mark -- TableViewDataSource & delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (![self isLogin]) {
        
        [self login];
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *className = _viewControllerNameAry[indexPath.row];
    
    UIViewController *subViewController = [[NSClassFromString(className) alloc] init];
    
    //加入我们和协议用的是一个界面 如果是加入我们  用 joinuS 这个字段来区分
    if ([_listNameAry[indexPath.row] isEqualToString:@"加入我们"]) {
        [subViewController setValue:_listNameAry[indexPath.row] forKey:@"joinUs"];
    }
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:(UIViewController*)subViewController animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listNameAry.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (MAIN_WIDTH < 375) {
        return  45;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellid = @"meTableViewCell";
    
    MeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MeTableViewCell" owner:self options:nil] lastObject];
    }
    
    cell.logoImageView.image = [UIImage imageNamed:_listNameAry[indexPath.row]];
    cell.nameLabel.text = _listNameAry[indexPath.row];
    [cell.nameLabel setFont:[UIFont systemFontOfSize:15]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

#pragma mark -- 初始化列表
- (void)initSubArray{
    
    _listNameAry = @[@"我的晒圈",@"我的关注",@"我的收藏",@"加入我们",@"服务反馈",@"账号设置",@"系统设置"];
    
    _viewControllerNameAry = @[@"我的晒圈",@"CAMyAttentionVC",@"CAMyCollectionVC",@"UseAgreementVC",@"CAServiceFeedbackVC",@"CAAccountSettingVC",@"CASystemSettingVC" ];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = YES;
    
//    判断是否登录
    if (![self isLogin]) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            [self login];
        });

    }else{
        
        __weak __typeof(self) weakSelf = self;
//        如果个人信息没有，那就获取信息
        if ([LoginSingleton sharedLoginSingleton].perInfoModel == nil) {
            
            [[LoginSingleton sharedLoginSingleton] getPerserInfoWithsuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [weakSelf accordingToView:[LoginSingleton sharedLoginSingleton].perInfoModel];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];

        }else{
            
            [self accordingToView:[LoginSingleton sharedLoginSingleton].perInfoModel];
        }
        
        
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
    
}

//#pragma mark -- 获取个人信息
//
//- (void)getPerserInfo{
//    
//    [self showIndicator:@"正在加载个人信息，请稍候..."];
//    
//    __weak __typeof(self) weakSelf = self;
//    
//    NSString *urlStr = [NSString stringWithFormat:@"/Api/Member/info?login_token=%@&member_id=%@",[LoginSingleton sharedLoginSingleton].token,[LoginSingleton sharedLoginSingleton].loginModel.ids];
//    
//    [HTTPManager get:GET_URLString(urlStr) success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [self hideIndicator];
//        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
//            
//            PersonalInformationModel *model = [[PersonalInformationModel alloc] init];
//            [model setValuesForKeysWithDictionary:responseObject[@"date"]];
//            
////            给单例赋值
//            [LoginSingleton sharedLoginSingleton].perInfoModel = model;
//            
//            //显示
//            [weakSelf accordingToView:model];
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [self hideIndicator];
//    }];
//}

//显示到View

- (void)accordingToView:(PersonalInformationModel *)model{
    
    if(model != nil){
    
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString:Get_HeadImage_UrlString(model.avatar)] placeholderImage:[UIImage imageNamed:@"个人注册.png"]];
            
            self.nickNameLabel.text = model.nickname;
            
            self.individualitySignatureLabel.text = model.mood;
            
        });
    
    }
}

#pragma mark -- 登录

- (void)login{
    
    __typeof(self) weakSelf = self;
    
    AlertView *login = [[AlertView alloc] initWithTitle:@"登录" contentText:@"你好" ButtonTitle:@"我靠" userAgreement:^{
        
        UseAgreementVC *agreementVC = [[UseAgreementVC alloc] init];
        weakSelf.hidesBottomBarWhenPushed = YES;
        
        [weakSelf.navigationController pushViewController:agreementVC animated:YES];
        
        weakSelf.hidesBottomBarWhenPushed = NO;
        
    }];
    login.Controller = self.navigationController;
    login.tabba = (FatherBarController *)self.tabBarController;
    
//    login.frame = CGRectMake((CGRectGetWidth(self.view.bounds) - kAlertWidth) * 0.5, - kAlertHeight - 30, MAIN_WIDTH-MAIN_WIDTH*0.09*2, kAlertHeight);
//    [self.view addSubview:login];
//
    login.loginBlock = ^(NSString *response,NSString *loginType){
        
        if ([loginType isEqualToString:@"1"]) {
            
            CALoginViewController *login = [[CALoginViewController alloc] init];
            
            login.loginBlock = ^(NSString *usid,NSString *loginType){
                
                if (![loginType isEqualToString:@"1"]) {
                    
                    [weakSelf thirdPartLoginWithInfo:usid withType:loginType];
                }
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            };
            
            weakSelf.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:login animated:YES];
            
            weakSelf.hidesBottomBarWhenPushed = NO;
            
        }else{
            
            [weakSelf thirdPartLoginWithInfo:response withType:loginType];
            
        }
        
    };
    
    login.registerBlock = ^{
        
        CAPersonalBusinessViewController *registerVC = [[CAPersonalBusinessViewController alloc] init];
        weakSelf.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:registerVC animated:YES];
        weakSelf.hidesBottomBarWhenPushed = NO;
        
    };
    
    [login show];
    
}


#pragma mark -- 三方登录
- (void)thirdPartLoginWithInfo:(NSString *)response withType:(NSString *)loginType{
    
    [self showIndicator:@"正在处理..."];
    
    __typeof(self) weakSelf = self;
    [HTTPManager post:GET_URLString(@"Api/Member/oauth_login") parameters:@{@"type":loginType,@"phone":@"2",@"value":response} success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        [weakSelf hideIndicator];
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf viewWillAppear:YES];
            });
            
            //保存本地
            [[LoginSingleton sharedLoginSingleton] loginSuccess:responseObject];
            
            [ShowMessage showCenterViewMessage:@"登录成功"];
            
        }else{
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf hideIndicator];
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
